import os

import chardet
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from genericpath import isfile
from scipy.interpolate import interp1d

rc = {"font.sans-serif": "Microsoft YaHei", "axes.unicode_minus": False}
sns.set(style="ticks", context="paper", rc=rc)
plt.rcParams["xtick.direction"] = "in"
plt.rcParams["ytick.direction"] = "in"


def parse_LD_data(filepath):
    if not os.path.exists(filepath):
        print("Filename Error: {}".format(filepath))
        return 0
    head_index, encoding = get_head_index(filepath)
    filename = os.path.basename(filepath)
    fileinfo = filename.split("_")
    lid_code = fileinfo[1]
    data_level = fileinfo[-1].split(".")[0]
    data = np.empty(0)
    if data_level not in ["L0", "L2"]:
        data_level = "L0"  # 针对系统1的L0级数据文件名无数据级别的补救
    if data_level == "L0":
        data_type = fileinfo[3]
        if lid_code == "LD1":
            if data_type == "Rm":
                data = pd.read_csv(
                    filepath, skiprows=head_index, encoding=encoding, sep="\s+"
                ).values
                data = data[:, ::2]
            elif data_type == "Ry":
                data = pd.read_csv(
                    filepath, skiprows=head_index, encoding=encoding, sep="\s+"
                ).values
                data = data[:, ::2]
            elif data_type == "Fe":
                data = pd.read_csv(
                    filepath, skiprows=head_index, encoding=encoding, sep="\s+"
                ).values
            else:
                print("Filename Error: {}".format(filepath))
        elif lid_code in ["LD2", "LJLD"]:
            if data_type in ["Ry", "Na", "Rm"]:
                data = pd.read_csv(
                    filepath, skiprows=head_index, encoding=encoding, sep="\s+"
                ).values
            else:
                print("Filename Error: {}".format(filepath))
        elif lid_code in ["LD3", "L3A", "L3B"]:
            if data_type in ["Ry", "Na", "Rm"]:
                data = pd.read_csv(
                    filepath, skiprows=head_index, encoding=encoding, sep="\s+"
                ).values
            else:
                print("Filename Error: {}".format(filepath))
        elif lid_code == "LD4":
            data = pd.read_csv(
                filepath,
                skiprows=head_index + 1,
                encoding=encoding,
                sep="\s+",
                header=None,
            ).values[:-1, :]
        else:
            print("Filename Error: {}".format(filepath))
    elif data_level == "L2":
        data_type = fileinfo[-3]
        if data_type in ["D", "T", "P", "N", "F"]:
            data = pd.read_csv(
                filepath, skiprows=head_index, encoding=encoding, sep="\s+"
            ).values
            data = data[:, :2]
        elif data_type in ["W", "V"]:
            if len(fileinfo) == 5:
                data = pd.read_csv(
                    filepath, skiprows=head_index, encoding=encoding, sep="\s+"
                ).values
                if data.dtype is np.dtype(object):
                    mask = data == "**********"
                    data[mask] = np.nan  # 针对数据存在**********的补救
                    data = data.astype("float")
                data = data[:, [0, 1, 3]]
            else:
                data = pd.read_csv(
                    filepath, skiprows=head_index, encoding=encoding, sep="\s+"
                ).values
                data = data[:, :2]
        elif data_type in ["DT"]:
            data = pd.read_csv(
                filepath,
                skiprows=head_index + 1,
                encoding=encoding,
                sep="\s+",
                header=None,
            ).values
            data = data[:-1, ::2]
        elif data_type in ["MW", "ZW"]:
            data = pd.read_csv(
                filepath,
                skiprows=head_index + 1,
                encoding=encoding,
                sep="\s+",
                header=None,
            ).values
            data = data[:-1, :2]
        else:
            print("Filename Error: {}".format(filepath))
    else:
        print("Filename Error: {}".format(filepath))
    # plt.figure()
    # plt.plot(data[:, 1:], data[:, 0])
    # plt.ylabel('Height/km')
    # plt.show()
    data[data == -9999] = np.nan
    return data


def get_head_index(filepath):
    try:
        with open(filepath, "r", encoding="utf-8") as f:
            filehead_all = f.readlines()
            encoding = "utf-8"
    except UnicodeDecodeError:
        with open(filepath, "r", encoding="gbk") as f:
            filehead_all = f.readlines()
            encoding = "gbk"
    head_index = 0
    while not (
            filehead_all[head_index].startswith("Rang")
            or filehead_all[head_index].startswith("Alt")
            or filehead_all[head_index].startswith("#End of Header")
    ):
        head_index += 1
    return head_index, encoding


def get_file_list(path):
    file_list = []
    for home, dirs, files in os.walk(path):
        for file in files:
            file_list.append(os.path.join(home, file))
    return file_list


if __name__ == "__main__":
    filepath = r"D:\1.Work\1.Data\新型地基\数据\对比数据20231119\系统3\SYS III NS\AL_L3B_V_20230820163000_L2.dat"
    filepath = r"D:\1.Work\1.Data\新型地基\数据\对比数据20231119\系统3\SYS III NS\AL_L3B_V_20230903210826_L2.dat"
    parse_LD_data(filepath)

    # filepath = r"D:\1.Work\1.Data\新型地基\数据\test_data2(少量)\系统4\L2\YC_LD4_DT_20230607143000_L2.txt"
    # filepath = r"D:\1.Work\1.Data\新型地基\数据\test_data2(少量)\系统4\L2\YC_LD4_MW_20230608143000_L2.txt"
    # filepath = r"D:\1.Work\1.Data\新型地基\数据\test_data2(少量)\系统4\L2\YC_LD4_ZW_20220825123000_L2.txt"
    # filepath = (
    #     r"D:\1.Work\1.Data\空间中心532nm多普勒激光雷达\YC数据\L0\YC_LD4_W_20230911143000_L0.txt"
    # )
    # data = parse_LD_data(filepath)

    # filepath = r"D:\1.Work\1.Data\新型地基\数据\模拟数据样例\系统1\L0\AL_LD1_355nm_Fe_DV_20230821140045_L0.dat"
    # parse_LD_data(filepath)

    # dirpath = r"D:\1.Work\1.Data\新型地基\数据\模拟数据样例"
    # file_list = get_file_list(dirpath)
    # for filepath in file_list:
    #     parse_LD_data(filepath)

    # dirpath = r"D:\1.Work\1.Data\新型地基\数据\模拟数据样例20230913"
    # file_list = get_file_list(dirpath)
    # for filepath in file_list:
    #     parse_LD_data(filepath)
